import { Card, Col, Row, Typography, Table, Button, Space, message, Modal, Form, Input, Select, DatePicker } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import { Iconify } from "@/components/icon";
import dayjs from 'dayjs';
import { debounce } from 'lodash';

interface Patient {
    id: number;
    name: string;
    age: number;
    gender: string;
    diagnosis: string;
    admissionDate: string;
    status: string;
}

// interface ElectronAPI {
//     ipcRenderer: {
//         invoke(channel: string, ...args: any[]): Promise<any>;
//         send(channel: string, ...args: any[]): void;
//         on(channel: string, func: (...args: any[]) => void): void;
//         removeAllListeners(channel: string): void;
//         searchPatients(keyword: string): Promise<Patient[]>;
//     };
// }

// declare global {
//     interface Window {
//         electronAPI: ElectronAPI;
//     }
// }

function PatientTable() {
    const [patients, setPatients] = useState<Patient[]>([]);
    const [loading, setLoading] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [currentPatient, setCurrentPatient] = useState<Patient | null>(null);
    const [form] = Form.useForm();
    const [filteredPatients, setFilteredPatients] = useState<Patient[]>([]);
    const [isSearching, setIsSearching] = useState(false);
    const [searchKeyword, setSearchKeyword] = useState('');

    useEffect(() => {
        fetchPatients();
    }, []);

    const fetchPatients = async () => {
        setLoading(true);
        try {
            // const data = await window.electronAPI.ipcRenderer.readPatients();
            const data = await window.electronAPI.ipcRenderer.invoke('read-patients');
            setPatients(data);
            setFilteredPatients(data);
        } catch (error) {
            console.error('Error fetching patients:', error);
            message.error('Failed to fetch patients');
        } finally {
            setLoading(false);
        }
    };

    const showAddModal = () => {
        setCurrentPatient(null);
        form.resetFields();
        setIsModalOpen(true);
    };

    const showEditModal = (patient: Patient) => {
        setCurrentPatient(patient);
        form.setFieldsValue({
            ...patient,
            admissionDate: patient.admissionDate ? dayjs(patient.admissionDate) : null
        });
        setIsModalOpen(true);
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            const patientData = {
                ...values,
                admissionDate: values.admissionDate ? values.admissionDate.format('YYYY-MM-DD') : new Date().toISOString()
            };

            if (currentPatient) {
                await window.electronAPI.ipcRenderer.invoke('update-patient', {
                    ...patientData,
                    id: currentPatient.id
                });
                message.success('Patient updated successfully');
            } else {
                await window.electronAPI.ipcRenderer.invoke('create-patient', patientData);
                message.success('Patient added successfully');
            }

            setIsModalOpen(false);
            fetchPatients();
        } catch (error) {
            console.error('Error saving patient:', error);
            message.error('Failed to save patient');
        }
    };

    const performSearch = async (keyword: string) => {
        try {
            setIsSearching(true);
            if (!keyword.trim()) {
                setFilteredPatients(patients);
                return;
            }

            const results = await window.electronAPI.ipcRenderer.searchPatients(keyword);
            setFilteredPatients(results);
        } catch (error) {
            console.error('Search error:', error);
            message.error('Search failed');
        } finally {
            setIsSearching(false);
        }
    };

    // Debounced search function
    const debouncedSearch = debounce(performSearch, 300);

    const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const keyword = e.target.value;
        setSearchKeyword(keyword);

        if (!keyword.trim()) {
            // If search box is empty, show all patients immediately
            setFilteredPatients(patients);
            return;
        }

        // Perform debounced search for non-empty keywords
        debouncedSearch(keyword);
    };

    const handleSearch = () => {
        performSearch(searchKeyword);
    };

    const handleDeletePatient = async (id: number) => {
        try {
            await window.electronAPI.ipcRenderer.invoke('delete-patient', id);
            message.success('Patient deleted successfully');
            fetchPatients();
        } catch (error) {
            console.error('Error deleting patient:', error);
            message.error('Failed to delete patient');
        }
    };

    const columns: ColumnsType<Patient> = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: 'Name',
            dataIndex: 'name',
            key: 'name',
            render: (text) => <Typography.Text strong>{text}</Typography.Text>,
        },
        {
            title: 'Age',
            dataIndex: 'age',
            key: 'age',
        },
        {
            title: 'Gender',
            dataIndex: 'gender',
            key: 'gender',
        },
        {
            title: 'Diagnosis',
            dataIndex: 'diagnosis',
            key: 'diagnosis',
        },
        {
            title: 'Admission Date',
            dataIndex: 'admissionDate',
            key: 'admissionDate',
            render: (date) => new Date(date).toLocaleDateString(),
        },
        {
            title: 'Status',
            dataIndex: 'status',
            key: 'status',
        },
        {
            title: 'Action',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        ghost
                        onClick={() => showEditModal(record)}
                    >
                        Edit
                    </Button>
                    <Button
                        danger
                        onClick={() => handleDeletePatient(record.id)}
                    >
                        Delete
                    </Button>
                </Space>
            ),
        },
    ];

    return (
        <div>
            <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
                <Col span={24}>
                    <Card>
                        <Space>
                            <Typography.Title level={4} style={{ margin: 0 }}>
                                Patient Management
                            </Typography.Title>
                            <Input.Search
                                placeholder="Search by name, diagnosis or status..."
                                // allowClear
                                enterButton="Search"
                                size="middle"
                                value={searchKeyword}
                                onChange={handleSearchChange}
                                onSearch={handleSearch}
                                loading={isSearching}
                                style={{ width: 350 }}
                            />
                            <Button
                                type="primary"
                                onClick={showAddModal}
                                icon={<Iconify icon="ic:baseline-plus" />}
                            >
                                Add Patient
                            </Button>
                        </Space>
                    </Card>
                </Col>
            </Row>

            <Row gutter={[16, 16]}>
                <Col span={24}>
                    <Card>
                        <Table
                            columns={columns}
                            dataSource={filteredPatients}
                            loading={loading || isSearching}
                            rowKey="id"
                            bordered
                            scroll={{ x: true }}
                        />
                    </Card>
                </Col>
            </Row>

            <Modal
                title={currentPatient ? "Edit Patient" : "Add New Patient"}
                open={isModalOpen}
                onOk={handleSubmit}
                onCancel={() => setIsModalOpen(false)}
                okText={currentPatient ? "Update" : "Create"}
                cancelText="Cancel"
                width={700}
            >
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{
                        status: 'stable',
                        gender: 'male'
                    }}
                >
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="name"
                                label="Name"
                                rules={[{ required: true, message: 'Please input patient name!' }]}
                            >
                                <Input placeholder="Patient name" />
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item
                                name="age"
                                label="Age"
                                rules={[{ required: true, message: 'Please input patient age!' }]}
                            >
                                <Input type="number" placeholder="Age" />
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item
                                name="gender"
                                label="Gender"
                                rules={[{ required: true }]}
                            >
                                <Select>
                                    <Select.Option value="male">Male</Select.Option>
                                    <Select.Option value="female">Female</Select.Option>
                                    <Select.Option value="other">Other</Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Form.Item
                        name="diagnosis"
                        label="Diagnosis"
                        rules={[{ required: true, message: 'Please input diagnosis!' }]}
                    >
                        <Input.TextArea rows={3} placeholder="Patient diagnosis" />
                    </Form.Item>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="admissionDate"
                                label="Admission Date"
                                rules={[{ required: true, message: 'Please select admission date!' }]}
                            >
                                <DatePicker style={{ width: '100%' }} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="status"
                                label="Status"
                                rules={[{ required: true }]}
                            >
                                <Select>
                                    <Select.Option value="stable">Stable</Select.Option>
                                    <Select.Option value="critical">Critical</Select.Option>
                                    <Select.Option value="recovering">Recovering</Select.Option>
                                    <Select.Option value="discharged">Discharged</Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </div>
    );
}

export default PatientTable;
